package com.ltu.util.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.ltu.util.datetime.DateTimeFormatUtile;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.alibaba.druid.pool.DruidDataSource;
import com.ltu.util.exception.SqlPrepareException;
/**
 * descriable: 实现 使用map或Json操作数据库表
 * @author 840473451
 *
 */
//@Component
public class BaseDao {
	protected Connection con = null;
	public Connection con2 = null;
	public PreparedStatement ps = null;
	public ResultSet rs = null;
//	private ResourceBundle database = ResourceBundle.getBundle("database4");
//	private String user = "";
//	private String pwd = "";
//	private String driver = "";
//	private String url = "";
	@Autowired
	@Qualifier("db1")
	DruidDataSource wfx;	
	public BaseDao() {
		// this.props = new Properties();
		// this.props.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
		// this.props.setProperty("java.naming.provider.url","localhost:1433");
		// 读出配置信息
		
//		driver = database.getString("jdbc.driver_class");
//		url = database.getString("jdbc.connection.url");
//		user = database.getString("jdbc.connection.username");
//		pwd = database.getString("jdbc.connection.password");
		
//		try {
//			conPool.createPool();
//		} catch (Exception e) {
//
//			e.printStackTrace();
//		}
	
	}
	private void writeLog(String message, SqlPrepareException e) {
//		logger.error(message, e);
//		logger.debug(message, e);
	}

	private void writeLog(String message) {
		String time = "";
		time = DateTimeFormatUtile.getNowDate();
//		logger.info("消息："+message);
	}

	// JDBC 连接
	public Connection get_JDBC_Con() {
		try {
		if (this.con == null || this.con.isClosed() ) {
		
				this.con=wfx.getConnection();
		}
			} catch (SQLException e) {

				e.printStackTrace();
			} catch (Exception e) {

				e.printStackTrace();
			}
		
	
		return this.con;
	}

	// JNDI 连接池 暂时有问题
	public Connection get_Con_JNDI() throws NamingException {
		// 初始化上下文
		if (con2 == null) {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myjndi");
			try {
				con2 = ds.getConnection();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		return con2;
	}

	// 释放资源
	public void closeAll() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}if (con != null) {
				//wfx.close();
				con.close();
				
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}
	}
	// 基本的Connection执行方式
	public int exceuteUpdate(String sql, Object[] param) {
		int num = 0;
		con = get_JDBC_Con();
		try {
			ps = con.prepareStatement(sql);
			if (param != null && param.length > 0) {
				for (int i = 0; i < param.length; i++) {
					ps.setObject(i + 1, param[i]);
				}
			}
			num = ps.executeUpdate();
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			closeAll();
		}
		return num;
	}

	/**
	 * 单行单表添加或修改 一张表多行添加 {AddOrUpdate="add",tableName="[vip].[dbo].vip_user",
	 * tableData={map1,map2,map3...} }
	 * **/
	// public int exceuteUpdate(Map<String, Object> data) {
	// int success = 0;
	// Map<String, Object> map = addOrUpdate_Single(data);
	// if (map != null) {
	// con = get_JDBC_Con();
	// try {
	// this.ps = con.prepareStatement(map.get("sql").toString());
	// String[] keyArr = (String[]) map.get("keys");
	// int len = keyArr.length;
	// for (int i = 0; i < len; i++) {
	// ps.setObject(i + 1, data.get(keyArr[i]));
	// }
	// success = ps.executeUpdate();
	// } catch (SQLException e) {
	//
	// e.printStackTrace();
	// }
	// }
	// return success;
	// }

	/***
	 * @describle 制作Insert语句
	 * @author 若尘
	 * @Time 2016-12-14
	 * @param data
	 *            表中一行的数据 ;
	 * @param tableName
	 *            表名
	 * @param rowName
	 *            当前行的标识
	 * @return Map 包涵sql语句 以及参数化所需的keyArr数组
	 */
	Map<String, Object> markAddSql(Map<String, Object> data, String rowName,
			String tableName) {
		Map<String, Object> map = null;
		String sql = "";
		List<String> keyArr = null;
		if (data != null && !data.isEmpty()) {
			map = new HashMap<String, Object>();
			int keyCount = data.size();
			keyArr = new ArrayList<String>();
			Set<String> keys = data.keySet();
			String sql1 = "INSERT  INTO " + tableName + " (";
			String sql2 = "VALUES(";
			int index = 0;
			for (Object object : keys) {
				keyArr.add( object.toString()) ;
				if (index < (keyCount - 1)) {
					sql1 += object + ",";
					sql2 += "?" + ",";
				} else {
					sql1 += object + ")";
					sql2 += "?" + ")";
				}
				index++;
			}
			sql = sql1 + "  " + sql2;
			map.put("sql", sql);
			map.put("paraKey", keyArr);
		}
		Map<String,Object>  paraMap=new HashMap<String,Object>();
		paraMap.put(rowName, map);
		return paraMap;
	}

	/***
	 * @describle 制作Update语句
	 * @author 若尘
	 * @Time 2016-12-15
	 * @param data
	 *            结构如下： {column=*,column=*}
	 * @param rowName
	 *            自己决定该行的key
	 * @param tableName
	 *            表名
	 * @return
	 */
  private	Map<String, Object> markUpdateSql(Map<String, Object> data, String rowName,
			String tableName) throws SqlPrepareException {
		Map<String, Object> paraMap = null;
		String sql = "";
		List<Object> paraKey =new ArrayList<Object>();
		if (data != null && !data.isEmpty()) {
			paraMap = new HashMap<String, Object>();
			Set<String> keys = data.keySet();
			int len = keys.size();
			String sql1 = "UPDATE " + tableName + "  set  ";			
			int index = 0;
			Map<String, Object> setMap = new HashMap<String, Object>();
			Map<String, Object> whereMap = new HashMap<String, Object>();
			for (String key : keys) {
				if(key.equals("or") || key.contains("@")){
					whereMap.put(key, data.get(key));
				}else{
					setMap.put(key, data.get(key));
				}			
			}			
			Set<String> setKey = setMap.keySet();
			int len2 = setKey.size();
			for (String key : setKey) {
				paraKey.add(key);
				if (index < len2 - 1) {
					sql1 += key + "=?, ";
				} else {
					sql1 += key + "=?";
				}
				index++;
			}
			Set<String> whereKeySet = whereMap.keySet();
			Map<String, Object>  temMap=null;
			int len3 = whereKeySet.size();
			if (len3 > 0) {
				temMap= markUpdateSql2(whereMap,paraKey);
				sql = sql1 + temMap.get("sql");			
			
			} else {
				throw new SqlPrepareException(this.getClass().getName() + " 缺少条件参数");
			}
			
			temMap.put("sql", sql);
			paraMap.put(rowName, temMap);
		}
		return paraMap;
	}
	/**
	 * 
	 * 
	 * @param whereKeySet 结构如下：
	 * 		{@column=*,or={@column="ss",@column={key=ss,value=""}},}
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private  Map<String,Object>  markUpdateSql2(Map<String,Object> whereMap,List<Object> paraKey){		
		Set<String> whereKeySet=whereMap.keySet();		
		Map<String, Object> column=null;
		  int index=0;
		  String sql2 = " WHERE 1=1 ";
		for (String key : whereKeySet) {		
			if(!key.equals("or"))	{paraKey.add(key);}					
			if (whereMap.get(key).getClass().getName() .equals("java.util.HashMap")) {
				 column = (Map<String, Object>) whereMap.get(key);				 
				 if(key.equals("or")){					 
					 Map<String,Object> orMap=  mark_Or_Sql(column, sql2);
					 sql2=orMap.get("sql").toString();
					 orMap.remove("sql");
					 paraKey.add(orMap);						
				}else if (column.get("key").equals("in")) {
					key = key.substring(1);			
					sql2 += " and " + key + "  in (";
					int len4 = 0;
					Map<String, Object> inMap = new HashMap<String, Object>();
					if (column.get("value").getClass().getName()
							.equals("[Ljava.lang.String;")) {
						String[] Str = (String[]) column.get("value");
						len4 = Str.length;
					} else if (column.get("value").getClass().getName()
							.equals("[I")) {
						int[] intStr = (int[]) column.get("value");
						len4 = intStr.length;
					}
					for (int i = 1; i <= len4; i++) {
						if (i < len4) {
							sql2 += "?,";
						} else {
							sql2 += "?)";
						}
					}
				} else {
					key = key.substring(1);			
					sql2 += " and " + key + "  " + column.get("key") + "  ?";
				}
			} else {
				key = key.substring(1);				
				sql2 += " and " + key + "=?  ";
			}
			index++;
		}
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("sql",sql2);		
		result.put("paraKey",paraKey);
		return result;
	}

	
	/***
	 * @describle 制作delete语句
	 * @author 若尘
	 * @Time 2016-12-15
	 * @param data
	 *            结构如下： {column=*,column=*}
	 * @param rowName
	 *            自己决定被的改行对象的key
	 * @param tableName
	 *            表名
	 * @return
	 */
	Map<String, Object> markDelSql(Map<String, Object> data, String rowName,
			String tableName) throws SqlPrepareException {
		Map<String, Object> paraMap = null;
		String sql = "";
		List<Object> paraKey =new ArrayList<Object>();
		if (data != null && !data.isEmpty()) {
			paraMap = new HashMap<String, Object>();
			String sql1 = "DELETE " + tableName + "   ";			
			int len3 = data.size();
			Map<String, Object> temMap=null;	
			if (len3 > 0) {
				temMap= markUpdateSql2(data,paraKey);
				sql = sql1 + temMap.get("sql");			
			
			} else {
				throw new SqlPrepareException(this.getClass().getName() + " 缺少条件参数");
			}
			
			temMap.put("sql", sql);
			paraMap.put(rowName, temMap);
		}
		return paraMap;
	}

	/***
	 * @describle 根据参数制作 Update insert delete 语句 以及保存参数数组 实现多表多行添加 修改 删除
	 * @author 若尘
	 * @Time 2016-12-14
	 * @param data
	 *            结构： { tableName1=[{column1="*",column2="*"...
	 *            flag=add}|tableName1={column1="*",column2="*"... },
	 *            tableName2=[{column1="*",column2="*"... }] }
	 * @return Map 结构：{ tableName=[{sql1="*",row1=[column1,column2,...]}],
	 *         tableName=[{sql1="*",row1=[column1,column2,...]}] }
	 */
	private Map<String, Object> addOrUpdate_MutilLine(Map<String, Object> data) {
		Map<String, Object> map = null;
		if (data != null && !data.isEmpty()) {
			map = new HashMap<String, Object>();
			Set<String> keys = data.keySet();
			int flag = 0;
			for (Object object : keys) {
				String typeNameStr = data.get(object.toString()).getClass()
						.getName();
				if (typeNameStr.equals("java.util.HashMap")
						|| typeNameStr.equals("net.sf.json.JSONObject")) {
					Map<String, Object> rowMap = (Map<String, Object>) data
							.get(object.toString());
					Map<String, Object> rowMap2 = null;
					if (rowMap.containsKey("flag")) {
						// flag=rowMap.get("flag").toString().toLowerCase();
						if (rowMap.get("flag").toString().toLowerCase()
								.equals("update")) {
							flag = 1;
						} else if (rowMap.get("flag").toString().toLowerCase()
								.equals("delete")) {
							flag = 2;
						} else {
							flag = 0;
						}
						rowMap.remove("flag");
					} else
						flag = 0;
					try {
						switch (flag) {
						case 1:
							rowMap2 = markUpdateSql(rowMap, "firstRow",
									object.toString());
							break;
						case 2:
							rowMap2 = markDelSql(rowMap, "firstRow",
									object.toString());
							break;
						case 0:
							rowMap2 = markAddSql(rowMap, "firstRow",
									object.toString());
							break;
						default:
							rowMap2 = markAddSql(rowMap, "firstRow",
									object.toString());
							break;
						}
					} catch (SqlPrepareException e) {

						writeLog(e.getMessage());
						e.printStackTrace();
					}
					// Map<String, Object> rowMap2 ="Update".equals(flag)?
					// markUpdateSql(rowMap, "firstRow",
					// object.toString()):markAddSQL(rowMap,
					// "firstRow", object.toString());
					map.put(object.toString(), rowMap2);

				} else if (data.get(object.toString()).getClass().getName()
						.equals("java.util.ArrayList")) {
					List<Map<String, Object>> resuList = new ArrayList<Map<String, Object>>();
					List<Map<String, Object>> para = (List<Map<String, Object>>) data
							.get(object.toString());
					int len = para.size();
					for (int i = 0; i < len; i++) {
						Map<String, Object> rowMap = para.get(i);
						Map<String, Object> rowMap2 = null;
						if (rowMap.containsKey("flag")) {
							if (rowMap.get("flag").toString().toLowerCase()
									.equals("update")) {
								flag = 1;
							} else if (rowMap.get("flag").toString()
									.toLowerCase().equals("delete")) {
								flag = 2;
							} else {
								flag = 0;
							}
							rowMap.remove("flag");
						} else
							flag = 0;
						try {
							switch (flag) {
							case 1:
								rowMap2 = markUpdateSql(rowMap, i + "",
										object.toString());
								break;
							case 2:
								rowMap2 = markDelSql(rowMap, i + "",
										object.toString());
								break;
							case 0:
								rowMap2 = markAddSql(rowMap, i + "",
										object.toString());
								break;
							default:
								rowMap2 = markAddSql(rowMap, i + "",
										object.toString());
								break;
							}
						} catch (SqlPrepareException e) {
							writeLog(e.getMessage());
							// writeLog(this.getClass().getName()+"出错了，" +
							// e.getMessage(),e);
							e.printStackTrace();
						}
						// Map<String, Object> rowMap2 = "Update".equals(flag)?
						// markUpdateSql(rowMap, i+"",
						// object.toString()):markAddSQL(rowMap,
						// i+"", object.toString());
						//map.put(object.toString(), rowMap2);
						resuList.add(rowMap2);
					}
					map.put(object.toString(), resuList);
				}
			}
		}
		return map;
	}

	/***
	 * @describle 将addOrUpdate_MutilLine 获取的sql 语句分别取出执行SQL
	 * @author 若尘
	 * @Time 2016-12-14
	 * @param data
	 *            结构： { tableName1=[{column1="*",column2="*"... }],
	 *            tableName2=[{column1="*",column2="*"... }] }
	 * @return 所有SQL的执行结果 successCount
	 */
	@SuppressWarnings("unchecked")
	public int AddMultiLine(Map<String, Object> data) {
		int successCount = 0;
		// 获取SQL语句和对应的参数数组
		Map<String, Object> paraMap = addOrUpdate_MutilLine(data);
		Set TableKey = data.keySet();
		this.con = null;
		try {
			con = this.get_JDBC_Con();
			// 关闭自动提交
		//	con.setAutoCommit(false);
			for (Object object : TableKey) {
				int len = 0;
				String sql = "";
				List<Object> rowIndex = null;
				if (data.get(object.toString()).getClass().getName()
						.equals("java.util.HashMap")) {
					// 获取参数集合
					Map<String, Object> singleRowMap = (Map<String, Object>) paraMap .get(object);
					sql = singleRowMap.get("sql").toString();
					rowIndex = (List<Object>) singleRowMap.get("firstRow");
					Map<String, Object> rowMap = (Map<String, Object>) data
							.get(object);
					// 表中的一行数据
					successCount += AddMultiLine(sql, con, rowMap,rowIndex);
				} else if (data.get(object.toString()).getClass().getName()
						.equals("java.util.ArrayList")) {
					// 获取当前表中的所有行对应的SQL 以及参数 数组 简之：获取多行参数数据
					List<Map<String, Object>> item = (List<Map<String, Object>>) paraMap
							.get(object);
					// 获取当前表的所有行数据
					List<Map<String, Object>> dataItemList = (List<Map<String, Object>>) data
							.get(object.toString());
					len = item.size();
					for (int i = 0; i < len; i++) {
						Map<String, Object> rowMap = item.get(i);
						sql = rowMap.get("sql").toString();
						rowIndex = (List<Object>) rowMap.get(i + "");
						Map<String, Object> dataSingle = dataItemList.get(i);
						successCount += AddMultiLine(sql, con, dataSingle,rowIndex );
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.closeAll();
		
		}
		return successCount;
	}

	/***
	 * @describle 重写AddMultiLine方法 封装添加语句的结果集 返回添加之后的主键 根据rowNum获取
	 * @author 若尘
	 * @Time 2017-03-29
	 * @param data
	 *            结构： { tableName1=[{column1="*",column2="*"... }],
	 *            tableName2=[{column1="*",column2="*"... }] }
	 * @return 所有SQL的执行结果 successCount
*{wfx.wfx_seckill={@order_stock_type={value=%私%, key=like}, flag=update, merchantDescriable=本店亏本大甩卖，最后3天全场5折，卖完就走！}, 
*wfx.wfx_vip={flag=update, nickname=淘气组, @nickname={value=%海%, key=like}, @id={value=[I@6509cc74, key=in}}} 
{wfx.wfx_seckill={firstRow=[@order_stock_type, merchantDescriable], sql=UPDATE wfx.wfx_seckill  set  merchantDescriable=? WHERE 1=1  and @order_stock_type  like  ?},
 wfx.wfx_vip={firstRow=[@nickname, @id, nickname], sql=UPDATE wfx.wfx_vip  set  nickname=? WHERE 1=1  and @nickname  like  ? and @id  in (?,?)}}
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> AddMultiLine2(Map<String, Object> data) {
		Map<String, Object> result = new HashMap<String, Object>();
		int successCount = 0;
		// 制作 SQL语句和对应的参数数组
		Map<String, Object> paraMap = addOrUpdate_MutilLine(data);  
		Set TableKey = data.keySet();
		this.con = null;
		try {
			con = this.get_JDBC_Con();
			// 关闭自动提交
//			con.setAutoCommit(false);
			for (Object object : TableKey) {
				int len = 0;
				String sql = "";
				String msg = "";
				int ruseltLine = 0;
				List<Object> paraKey =null;
				Map<String, Object> GeneratedKeys = new HashMap<String, Object>();
				if (data.get(object.toString()).getClass().getName()
						.equals("java.util.HashMap")) {
					// 获取参数集合
					Map<String, Object> tablePara = (Map<String, Object>) paraMap.get(object);
					Set<String>  keys2=tablePara.keySet();
					Map<String, Object> singleRowMap=null;
					for (String key : keys2) {
						singleRowMap=(Map<String, Object>) tablePara.get(key);						
					}					
					sql = singleRowMap.get("sql").toString();
					paraKey = (List<Object>) singleRowMap.get("paraKey");
					Map<String, Object> rowMap = (Map<String, Object>) data
							.get(object);
					// 表中的一行数据
					ruseltLine = AddMultiLine(sql, con, rowMap, paraKey); //执行
					// 2017-03-29 获取添加之后的主键
					this.rs = ps.getGeneratedKeys();
					msg = "执行的sql:" + sql;
					GeneratedKeys = printSql(rs, msg, GeneratedKeys, 1,
							ruseltLine);
					successCount += ruseltLine;
					result.put(object.toString(), GeneratedKeys);
				} else if (data.get(object.toString()).getClass().getName()
						.equals("java.util.ArrayList")) {
					// 获取当前表中的所有行对应的SQL 以及参数 数组 简之：获取多行参数数据
					List<Map<String, Object>> item = (List<Map<String, Object>>) paraMap
							.get(object);
					// 获取当前表的所有行数据
					List<Map<String, Object>> dataItemList = (List<Map<String, Object>>) data
							.get(object.toString());
					len = item.size();
					for (int i = 0; i < len; i++) {
						Map<String, Object> rowMap = (Map<String, Object>) item.get(i).get(i+"");
						sql = rowMap.get("sql").toString();
						paraKey = (List<Object>) rowMap.get("paraKey");
						Map<String, Object> dataSingle = dataItemList.get(i);
						ruseltLine = 0;
						ruseltLine = AddMultiLine(sql, con, dataSingle,
								paraKey);
						// 2017-03-29 获取添加之后的主键
						this.rs = ps.getGeneratedKeys();
						msg = "执行的sql:" + sql;
						GeneratedKeys = printSql(rs, msg, GeneratedKeys, i + 1,
								ruseltLine);
						successCount += ruseltLine;
					}
					result.put(object.toString(), GeneratedKeys);
				}
			}
			//con.commit();
		} catch (SQLException e) {

//			try {
//				// if(!con.isClosed()){
//				// con.rollback();
//				// con.setAutoCommit(true);
//				// }
//				con.rollback();
//				con.setAutoCommit(true);
//			} catch (SQLException e1) {
//
//				e1.printStackTrace();
//			}
			e.printStackTrace();
		} finally {
			// effectCount 受影响的总行数
			result.put("effectCount", successCount);
			this.closeAll();
			return result;
			
		}
		
	}

	private Map<String, Object> printSql(ResultSet rs, String msg,
			Map<String, Object> GeneratedKeys, int i, int ruseltLine) {
		try {
			if (ruseltLine > 0) {
				if (rs.next()) {
					GeneratedKeys.put((i) + "", rs.getInt(1));
					msg += " 插入成功,主键为：" + rs.getInt(1);
				} else {
					GeneratedKeys.put(i + "", ruseltLine);
					msg += " 修改成功  " + ruseltLine + "行受影响";
				}
			} else {
				GeneratedKeys.put(i + "", ruseltLine);
				msg += "  操作失败" + ruseltLine + "行受影响";
			}
			System.out.println(msg);
		} catch (SQLException e) {

			e.printStackTrace();
		}finally{
			this.writeLog(msg);
			return GeneratedKeys;
		}
		
	}

	/***
	 * @describle 分页查询 支持 in like 等关键字
	 * @param paraMap
	 *            {sql=*,para={column=*,column2=*...},pageMap={tableName="表名",Id
	 *            ="自增列名称",currentPage=2,pageSize=10}}
	 * 
	 * @return dataMap 结构如下： { record=100, tableName=[{},{},{}]}
	 * @throws SqlPrepareException
	 * @author 若尘
	 * @Time 2016-12-16  2017-05-06 :在mysql下不适用
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> markPage(Map<String, Object> paraMap)
			throws SqlPrepareException {
		Map<String, Object> resultMap = null;
		String whereSql = "";
		String countSQL = "";
		String countWhere = "";
		List<Object> paraKey=null;
		try {
			// 是否包涵分页所需条件
			if (paraMap != null && !paraMap.isEmpty()
					&& paraMap.containsKey("pageMap")) {
				Map<String, Object> pageMap = (Map<String, Object>) paraMap
						.get("pageMap");
				countSQL = "Select  count(1) as total From "
						+ getFrom_after_sql(paraMap.get("sql").toString());
				countWhere = "  Where 1=1 ";
				resultMap = new HashMap<String, Object>();
				List<Object> paraKey2 = null;
				Map<String, Object> para = null; // 条件数据
				whereSql = " Where  1=1 "; // 条件语句
				// wherePagesql 分页条件段语句1
				int index = pageMap.get("Id").toString().indexOf(".");
				String maxId = "_page."
						+ (pageMap.get("Id").toString().substring(index + 1));
				String wherePagesql = " And " + pageMap.get("Id") + ">"
						+ "(Select ISNUll(MAX(" + maxId
						+ "),0) From (Select top  (" + pageMap.get("pageSize")
						+ "*(" + pageMap.get("currentPage") + "-1))  "
						+ pageMap.get("Id") + "  From  "
						+ this.getFrom_after_sql(paraMap.get("sql").toString());
				// wherePagesql 分页条件段语句2
				String wherePagesql2 = "  order by  " + pageMap.get("Id")
						+ " ) as _page  ) order by " + pageMap.get("Id")
						+ " asc";

				// 是否包涵数据数据筛选条件
				if (paraMap.containsKey("para")
						&& (paraMap.get("para").getClass().getName()
								.equals("java.util.HashMap") || paraMap
								.get("para").getClass().getName()
								.equals("net.sf.json.JSONObject"))) {
					para = (Map<String, Object>) paraMap.get("para");
					// 制作SQL KeysList集合
					Map<String,Object>whereMap= markAndSql(para);
					String whereSql2 = whereMap.get("sql").toString();
					paraKey=(List<Object>) whereMap.get("paraKey");
					countWhere += whereSql2;
					whereSql += whereSql2;
				}
				
				
				whereSql = whereSql + wherePagesql + whereSql + wherePagesql2;
				String sql = paraMap.get("sql").toString() + whereSql;
				countSQL += countWhere;
				// 开始执行查询
				this.con = this.get_JDBC_Con();
				// 查询总记录数
				List<Map<String, Object>> totalList = exceQuerySQL(countSQL,
						con, para, false,paraKey);

				Map<String, Object> totalMap = totalList.get(0);
				resultMap.put("record", totalMap.get("total"));
				// 查询数据
				List<Map<String, Object>> dataRows = exceQuerySQL(sql, con,
						para, true,paraKey);
				resultMap.put(pageMap.get("tableName").toString(), dataRows);

			} else {
				writeLog(this.getClass().getName()
						+ "出错， method:markPageSql"
						+ "pageMap集合应包涵  Id(自增列)  tableName  currentPage  pageSize 等参数");
				throw new SqlPrepareException(this.getClass().getName()
						+ "出错， method:markPageSql"
						+ "pageMap 必须包涵  tableName  currentPage  pageSize 等参数");
			}
		} catch (Exception e) {
			writeLog(this.getClass().getName()
					+ "出错， method:markPageSql"
					+ "pageMap集合应包涵  Id(自增列)  tableName  currentPage  pageSize 等参数"
					+ "  原错误消息：" + e.getMessage());
			e.printStackTrace();
		} finally {
			this.closeAll();
		}
		return resultMap;
	}
	/**
	 * 
	 * @param sql
	 * @return
	 */
	private String getFrom_after_sql(String sql) {
		String from_after_sql = "";
		int index = sql.toLowerCase().indexOf("from");
		from_after_sql = sql.substring(index + 4);
		return from_after_sql;
	}

	/**
	 * @describle where语句后的and语句拼接。。。
	 * @author 若尘
	 * @param para
	 *            {columnName={key=<=,value="sss"},columnName={key=in,value=[]},
	 *            columnNmae
	 *            ="",or={columnName={key=<=,value="sss"},columnName={key
	 *            =in,value=[]},columnNmae=""}}
	 * @return whereSql
	 * @Time 2016-12-16
	 */
	private Map<String, Object>  markAndSql(Map<String, Object> para) {
		Map<String, Object> resulMap = null;
		String sql = "";		
		if (para != null && !para.isEmpty()) {
			resulMap = new HashMap<String, Object>();
			Set<String> keys = para.keySet();				
			int index = 0;
			List<Object> paraKey = new ArrayList<Object>();
			// Iterator it=keys.iterator();
			// while(it.hasNext()){
			// String key= it.next().toString();
			// columnArr[index]=key;
			// sql=" and "+key+"=? ";
			// index++;
			// }
			Map<String, Object> column = null;
			Object columnValue = null;
			for (String key : keys) {
				if(!key.equals("or")){  paraKey.add(index, key); }
				System.out.println(StrFromArray.arrayToStr(paraKey,','));
				String typeNameStr = para.get(key).getClass().getName();
				if (typeNameStr.equals("java.util.HashMap")
						|| typeNameStr.equals("net.sf.json.JSONObject")) {
					column = (Map<String, Object>) para.get(key);
					if (key.toLowerCase().equals("or")) {
						Map<String,Object> orMap  = this.mark_Or_Sql(column, sql);
						sql =orMap.get("sql").toString();
						orMap.remove("sql");
						paraKey.add( orMap);
						System.out.println(StrFromArray.arrayToStr(paraKey,','));
					} else {						
						if (column.get("key").equals("in")) {
							sql += " and " + key + "  in (";  									
							int len2 = 0;
							Map<String, Object> inMap = new HashMap<String, Object>();
							String typeName = column.get("value").getClass()
									.getName();
							if (typeName.equals("[I") ){
								len2 = ((int[]) column.get("value")).length;
							} else if (typeName.equals( "[Ljava.lang.String;")) {
								len2 = ((String[]) column.get("value")).length;
							}else if(typeName.equals("java.util.ArrayList")){
								List  lis= (List) (column.get("value"));
								len2 =lis.size();
							}							
							for (int i = 1; i <= len2; i++) {
								if (i < len2) {
									sql += " ?,";
								} else {
									sql += " ? )";
								}
							}
						} else {
							sql += " and " + key + "  " + column.get("key") + "  ?";
						}
					}
				} else {
					sql += " and " + key + "=?";
				}
				index++;
			}
			resulMap.put("sql", sql);
			resulMap.put("paraKey", paraKey);
		}
		return resulMap;
	}
	/**
	 * 
	 * @param {column="", column={key=in,value=Array},column={key=like,value="%ss%"},column={key=>,value=100}}
	 * @param sql 
	 * @return   sql:  and (column="" or column in (1,2,3) or column like '%ss%')
	 */
	@SuppressWarnings("unchecked")
	private Map<String,Object> mark_Or_Sql(Map<String, Object> para, String sql) {
		Map<String,Object> result=new HashMap<String,Object>();
		List<String> paraKey = new ArrayList<String>();
		try {
			if (para != null && !para.isEmpty()) {
				sql += " and  (";
				String	sql2="";			
				String or = " ";
				Object[]  keys=		 (Object[]) para.keySet().toArray();			
				int len = keys.length;
				Map<String, Object> column = null;
				List<Map<String, Object>> list = null;
				for (int j = 0; j < len; j++) {
					String key = keys[j].toString();
					paraKey.add(key);
					or = j > 0 ? " or " : "  ";
					String typeNameStr = para.get(key).getClass().getName();				
					if (typeNameStr.equals("java.util.HashMap")
							|| typeNameStr.equals("net.sf.json.JSONObject")) {					
						column = (Map<String, Object>) para.get(key);
						key= key.indexOf("@")>-1?key.substring(1):key;						
						sql2 = markOrSql(column, key, sql2, or);
					}
					else if (typeNameStr.equals("net.sf.json.JSONArray")
							|| typeNameStr.equals("java.util.ArrayList")) {
						list = (List<Map<String, Object>>) para.get(key);
						int len2 = list.size();
						for (int i = 0; i < len2; i++) {
							column = list.get(0);
							key= key.indexOf("@")>-1?key.substring(1):key;
							sql2 = markOrSql(column, key, sql2, or);
						}
					} else {
						key= key.indexOf("@")>-1?key.substring(1):key;
						sql2 += or + key + "=? ";
					}
				}
				sql +=(sql2+ "  ) ");
			}
		} catch (Exception e) {

			e.printStackTrace();
		}		
		result.put("sql", sql);
		result.put("or", paraKey);
		return  result;
	}

	/**
	 * 
	 * @param {key=<,value=""}|| {key=in,value=Array} || {key=in,value=Array}|| {key=like,value="%ss%"}
	 * @param key  对应的条件列名
	 * @param sql
	 * @param or
	 * @return  sql: or column=""  ||  or column in (1,2,3)  || or column like "%ss%"
	 */
	public String markOrSql(Map<String, Object> column, String key, String sql,
			String or) {		
		if (column.get("key").equals("in")) {
			sql += or + key + "  " + column.get("key") + "(";
			int len2 = 0;
			String typeName = column.get("value").getClass().getName();	
			if (typeName.equals( "[I") ) {
				len2 = ((int[]) column.get("value")).length;
			} else if (typeName.equals( "[Ljava.lang.String;")) {
				len2 = ((String[]) column.get("value")).length;
			}else if(typeName.equals("java.util.ArrayList")){
				List  lis= (List) (column.get("value"));
				len2 =lis.size();
			}
			for (int i = 1; i <= len2; i++) {
				if (i < len2) {
					sql += "?,";
				} else {
					sql += "?)";
				}
			}
		} else {
			sql += or + key + "  " + column.get("key") + "  ?";
		}
		return sql;
	}

	/***
	 * descriable:{ {
	 * tableName1={sql="*",tableName="*",Id="*",asec="*",para={column
	 * ={key="in",value=[]}|colum={key="like",value="%*%"}|column="*"} }
	 * tableName2
	 * ={sql="*",tableName="*",Id="*",asec="*",para={column={key="in",value
	 * =[]}|colum={key="like",value="%*%"}|column="*"} }
	 * 
	 * }
	 * 
	 * @param paraMap
	 * @return
	 */
	public Map<String, Object> NoPageQuerys(Map<String, Object> paraMap) {
		Map<String, Object> resultMap = null;
		try {
			if (paraMap != null && paraMap.size() > 0) {
				resultMap = new HashMap<String, Object>();
				Set<String> keys = paraMap.keySet();
				Iterator its = keys.iterator();
				while (its.hasNext()) {
					String key = its.next().toString();
					List<Map<String, Object>> tableList = null;
					Map<String, Object> tableMap = (Map<String, Object>) paraMap
							.get(key);
					try {
						tableList = (List<Map<String, Object>>) this
								.NoPageQuery(tableMap);
						resultMap.put(key, tableList);
					} catch (SqlPrepareException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			writeLog(this.getClass().getName() + "出错，" + "  原错误消息："
					+ e.getMessage());
			e.printStackTrace();
		} finally {

					this.closeAll();
			
		}
		return resultMap;
	}

	/***
	 * @describle 不分页Select语句查询
	 * @param paraMap
	 *            结构： {
	 *            sql="*",tableName="*",Id="*",asec="*",para={column={key="in"
	 *            ,value=[]}|colum={key="like",value="%*%"}|column="*"} }
	 * @return resultMap 结构：
	 *         {tableName==[{column="*",column="*"...},{column="*",
	 *         column="*"...}...]}
	 * @Time 2016-12-20
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> NoPageQuery(Map<String, Object> paraMap ) throws SqlPrepareException {
		List<Map<String, Object>> tableSingle = null;
		String whereSql = "";

		List<Object> paraKey = null; // 条件key
		Map<String, Object> para = null; // 条件数据		
		whereSql = " Where  1=1 ";
		// 是否包涵数据数据条件
		if (paraMap.containsKey("para")
				&& (paraMap.get("para").getClass().getName()
						.equals("java.util.HashMap") || paraMap.get("para")
						.getClass().getName().equals("net.sf.json.JSONObject"))) {
			para = (Map<String, Object>) paraMap.get("para");
			// 制作SQL KeysList集合	
		   Map<String,Object> wherMap=	 markAndSql(para);
			whereSql +=wherMap.get("sql").toString();
			paraKey=(List<Object>) wherMap.get("paraKey");
		}

		String  asc=paraMap.containsKey("asc")==true?(" "+paraMap.get("asc")):"  ";
		String groupBySql=paraMap.containsKey("sortId")==true?("  order by  "+paraMap.get("sortId")+asc):" ";
		String sql = paraMap.get("sql").toString() + whereSql + groupBySql;		
		// 开始执行查询
		con = this.get_JDBC_Con();
		tableSingle = exceQuerySQL(sql, con, para, false,paraKey);
		outExceSQL(para,sql);

		return tableSingle;
	}
	
	/***
	 * @describle 制作结果集 将结果集转换成List<Map>集合 每个List是一张表 每个Map代表一行数据
	 * @author 若尘
	 * @Time 2016-12-14
	 */
	public List<Map<String, Object>> markResult(ResultSet rs) {
		List<Map<String, Object>> list = null;
		try {
		if (rs != null) {
			list = new ArrayList<Map<String, Object>>();			
				ResultSetMetaData rsdata = rs.getMetaData();
				int columnCount = rsdata.getColumnCount();
			//	System.out.println("getColumnLabel:"+rsdata.getColumnLabel(1));
			//	System.out.println("getColumnName:"+rsdata.getColumnName(1));
				
				while (rs.next()) {
					Map<String, Object> map = new HashMap<String, Object>();
					for (int i = 1; i <= columnCount; i++) {						
						String key = rsdata.getColumnLabel(i);
						map.put(key, rs.getObject(key));
					}
					list.add(map);
				}
			} 
		}catch (SQLException e) {

			Map<String,Object> map=new HashMap<String,Object>();
			map.put("errorMsg", e.getMessage());
			list.add(map);
			e.printStackTrace();
		}finally{
			return list;
		}
		
	}

	/***
	 * @describle 执行增删改语句
	 * @author 若尘
	 * @Time 2016-12-14
	 * @param sql
	 * @param keys
	 * @param paraMap
	 * @param con
	 * @return update: 2017-03-26 修改 加入事务管理机制
	 */
	int AddMultiLine(String sql, Connection con, Map<String, Object> paraMap,
			List<Object> parakey) {
		int flag = 0;
		int[] flags = null;
		if (con != null) {
			try {
				appendPS(sql, con, paraMap, false,parakey);
//				flags=jdbcTemplate.batchUpdate(sql,(BatchPreparedStatementSetter) ps);
				
				flags = ps.executeBatch();
				// flag= ps.executeUpdate();
			} catch (SQLException e) {

//				try {
//					if (!con.isClosed()) {
//						con.rollback();
//						System.out.println("指定sql：" + sql + "插入失败，回滚！");
//						con.setAutoCommit(true);
//					}
//				} catch (SQLException e1) {
//
//					e1.printStackTrace();
//				}
				this.writeLog("指定sql：" + sql + "插入失败，回滚！");
				System.out.println("指定sql：" + sql + "插入失败，回滚！");
				e.printStackTrace();
			}catch(Exception e){
				
			}
		}
		for (int i = 0; i < flags.length; i++) {
			flag += flags[i];
		}
		return flag;
	}

	/***
	 * @author ruochen
	 * @descrition 执行查询语句返回List<Map> List即一张表，Map即一行
	 * @param sql
	 * @param con
	 * @param para
	 * @param paraKey [key,key2,{key3:[keys1,keys2]},key4]
	 * @return
	 */
	List<Map<String, Object>> exceQuerySQL(String sql, Connection con,
			Map<String, Object> para, boolean isPage,List<Object> parakey) {
		List<Map<String, Object>> tableResult = null;
		try {
			appendPS(sql, con, para, isPage,parakey);
			System.out.println(sql);
			rs = ps.executeQuery();
			// rs.next();
			tableResult = markResult(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll();
		}

		return tableResult;
	}
	/***
	 * @author ruochen
	 * @descrition 执行查询语句返回List<Map> List即一张表，Map即一行
	 * @param sql
	 * @param con
	 * @param para
	 * @param paraKey
	 * @return
	 * @time 2017-05-06
	 */
	private List<Map<String, Object>> mysqlExceQuerySQL(String sql, Connection con,
			Map<String, Object> para, boolean isPage,List<Object> paraKey) {
		List<Map<String, Object>> tableResult = null;
		try {			
			mysql_appendPS(sql, con, para, isPage,paraKey);			
			rs = ps.executeQuery();		
			tableResult = markResult(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} 

		return tableResult;
	}
	/***
	 * @descrition 写入PreparedStatement对象所需的参数
	 * @author 若尘
	 * @param sql
	 * @param con
	 * @param para
	 *            一行对象 即所有列对应的keyValue值
	 * @param paraKey
	 *            单纯的 coulumnName
	 * @throws SQLException
	 * @time 2016-12-20
	 */
	private  void appendPS(String sql, Connection con, Map<String, Object> para,
			boolean isPage,List<Object> parakey) throws SQLException {
		if (con != null) {
			this.ps = con
					.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			if (para != null && !para.isEmpty()) {
				int index = 1;
				index = appendPS_or_sql(para, index,parakey);
				if (isPage) {
					appendPS_or_sql(para, index, parakey);
				}
				ps.addBatch();
			}
		}
	}
	
	
	/***
	 * @descrition 写入PreparedStatement对象所需的参数
	 * @author 若尘
	 * @param sql
	 * @param con
	 * @param para
	 *            一行对象 即所有列对应的keyValue值
	 * @param paraKey
	 *            单纯的 coulumnName
	 * @throws SQLException
	 * @time 2017-05-08
	 */
	private  void mysql_appendPS(String sql, Connection con, Map<String, Object> para,
			boolean isPage,List<Object> paraKey) throws SQLException {
		if (con != null) {
			this.ps = con
					.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			if (para != null && !para.isEmpty()) {
				int index = 1;
				index = appendPS_or_sql(para, index,paraKey);				
				ps.addBatch();
			}
		}
	}

	/**	 
	 * 
	 * 
	 * @param column_or
	 * @param index
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings({ "unchecked", "finally" })
	private int appendPS_or_sql(Map<String, Object> column_or, int index,List<Object> paraKey)
			 {			
		try {
			int len = paraKey.size();
			String typeNameStr = "";
			Map<String, Object> column = null;
			List<Map<String, Object>> list = null;
			Object columnValue = null;
			for (int i = 0; i < len; i++) {
				typeNameStr=paraKey.get(i).getClass().getName();
				if(typeNameStr.equals("java.util.HashMap")
						|| typeNameStr.equals("net.sf.json.JSONObject")){				
					Map<String,Object> orKey=(Map<String, Object>) paraKey.get(i);
					List<Object> paraKey2=(List<Object>) orKey.get("or");
					column=(Map<String, Object>) column_or.get("or");
					index=appendPS_or_sql(column,index,paraKey2);
				}else {				
					typeNameStr = (column_or.get(paraKey.get(i).toString())).getClass() .getName(); 
					if (typeNameStr.equals("java.util.HashMap") || typeNameStr.equals("net.sf.json.JSONObject")) {
						column=(Map<String, Object>) column_or.get(paraKey.get(i).toString());
							index = setPS(column, index);   //setPS 负责将key  value 结构的条件对象 的数据读取					
					} else if (typeNameStr.equals("net.sf.json.JSONArray")
							|| typeNameStr.equals("java.util.ArrayList")) {
						list = (List<Map<String, Object>>) column_or.get(paraKey.get(i).toString());
						int len2 = list.size();
						for (int j = 0; j < len2; j++) {
							index = setPS(list.get(j), index);
						}
					} else {
						columnValue = column_or.get(paraKey.get(i).toString());
						ps.setObject(index, columnValue);
					}
					if (i < len - 1) {
						index++;
					}
				}
			}
		}catch (Exception e) {
				closeAll();
			e.printStackTrace();			
		}finally{
			return index;
		}		
	}
	
	@SuppressWarnings("unchecked")
	private int appendPS_or_sql2(Map<String, Object> column_or, int index,List<Object> parakey)
			throws SQLException {
		
		int len = parakey.size();
		String typeNameStr = "";
		Map<String, Object> column = null;
		List<Map<String, Object>> list = null;
		Object columnValue = null;
		for (int i = 0; i < len; i++) {
			typeNameStr=	parakey.get(i).getClass().getName();
			if(typeNameStr.equals("java.util.HashMap")
					|| typeNameStr.equals("net.sf.json.JSONObject")){
				Map<String,Object> orMap=(Map<String, Object>) parakey.get(i);
				Map<String,Object> orColumn=(Map<String, Object>) column_or.get("or");
				List<Object> orParaKey=(List<Object>) orMap.get("or");
				index=	appendPS_or_sql2(orColumn,index,orParaKey);
			}else {
				typeNameStr = column_or.get(parakey.get(i)).getClass() .getName(); 
				if (typeNameStr.equals("java.util.HashMap")
						|| typeNameStr.equals("net.sf.json.JSONObject")) {					
						column = (Map<String, Object>) column_or.get(parakey.get(i));				
						index = setPS(column, index);					
				} else if (typeNameStr.equals("net.sf.json.JSONArray")
						|| typeNameStr.equals("java.util.ArrayList")) {					
					list = (List<Map<String, Object>>) column_or.get(parakey.get(i));
					int len2 = list.size();
					for (int j = 0; j < len2; j++) {
						index = setPS(list.get(j), index);
					}
				} else {
					columnValue = column_or.get(parakey.get(i));
					ps.setObject(index, columnValue);
				}
				if (i < len - 1) {
					index++;
				}							
			}
		}
		return index;
	}
	
	
	
	
	
	/**
	 * descriable:该方法只负责结构为  column={key="*",value=*}的参数条件
	 * 
	 * @param column 只能是一个对象 一条数据  参数结构 {}|| {key="like",value="%sss%"} || {key=in,value=Array}
	 * @param index
	 * @return
	 * @throws SQLException
	 */
	@SuppressWarnings("unchecked")
	private int setPS(Map<String, Object> column, int index){
		try {
		if (column != null) {
			if (column.containsKey("key") ) {
				if( column.get("key").equals("in")){
					int len2 = 0;
					List<Object> list = new ArrayList<Object>();
					String typeName = column.get("value").getClass().getName();
					if (typeName.equals( "[I") ){
						len2 = ((int[]) column.get("value")).length;
						int[] intarr = ((int[]) column.get("value"));
						for (int i = 0; i < len2; i++) {
							list.add(intarr[i]);
						}

					} else if (typeName.equals( "[Ljava.lang.String;") ){
						len2 = ((String[]) column.get("value")).length;
						String[] intarr = ((String[]) column.get("value"));
						for (int i = 0; i < len2; i++) {
							list.add(intarr[i]);
						}
						
					}else if (typeName.equals( "java.util.ArrayList")) {
						list=(ArrayList<Object>) column.get("value");
						len2=list.size();
					}

					for (int j = 0; j < len2; j++) {
					
							this.ps.setObject(index, list.get(j));
						
						if (j < len2 - 1) {
							index++;
						}
					}
				}else {
					String likeStr = column.get("value").toString();
					ps.setObject(index, likeStr);					
				}
			}
		}
		} catch (SQLException e) {
			closeAll();
			e.printStackTrace();
		}
		return index;
	}
	/***
	 * @describle 分页查询 支持 in like 等关键字
	 * @param paraMap
	 *            {sql=*,para={column=*,column2=*...},pageMap={tableName="表名",sortId
	 *            ="排序",currentPage=2,pageSize=10}}
	 * 
	 * @return dataMap 结构如下： { record=100, tableName=[{},{},{}]}
	 * @throws SqlPrepareException
	 * @author 若尘
	 * @Time  2017-05-06
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> mysqlPage(Map<String, Object> paraMap)
			throws SqlPrepareException {
		Map<String, Object> resultMap = null;
		String whereSql = "";
		String countSQL = "";
		String countWhere = "";
		try {
			// 是否包涵分页所需条件
			if (paraMap != null && !paraMap.isEmpty()
					&& paraMap.containsKey("pageMap")) {
				Map<String, Object> pageMap = (Map<String, Object>) paraMap
						.get("pageMap");
				if(!pageMap.containsKey("pageSize")||!pageMap.containsKey("currentPage")){
					writeLog(this.getClass().getName() + "出错， method:mysqlPage" + "pageMap集合应包涵    tableName  currentPage  pageSize 等参数");
					throw new SqlPrepareException(this.getClass().getName()
							+ "出错， method:markPageSql" + "pageMap 必须包涵  tableName  currentPage  pageSize 等参数");
				}
				countSQL = "Select  count(1) as total From "
						+ getFrom_after_sql(paraMap.get("sql").toString()); //获取表名  
				countWhere = "  Where 1=1 ";
				resultMap = new HashMap<String, Object>();
				List<Object> paraKey = null; // 条件key
				List<Object> paraKey2 = null;
				Map<String, Object> para = null; // 条件数据
				whereSql = " Where  1=1 "; // 条件语句				
				
				// wherePagesql 分页条件段语句2
				String asc=(String) (pageMap.containsKey("asc")==true?("  "+pageMap.get("asc")) :"  asc");
				int currentPage=Integer.parseInt(pageMap.get("currentPage").toString());
				int pageSize=Integer.parseInt(pageMap.get("pageSize").toString());
				int startRecord=(currentPage-1)*pageSize;
				String sortSql= pageMap.containsKey("sortId")==true?("  order by  " + pageMap.get("sortId") + asc):" ";
				String wherePagesql2 = sortSql+" LIMIT  "+startRecord+","+pageSize;
				// 是否包涵数据数据筛选条件
				if (paraMap.containsKey("para")
						&& (paraMap.get("para").getClass().getName()
								.equals("java.util.HashMap") || paraMap
								.get("para").getClass().getName()
								.equals("net.sf.json.JSONObject"))) {
					para = (Map<String, Object>) paraMap.get("para");
					// 制作SQL KeysList集合
					Map<String,Object> temp= markAndSql(para);
					countWhere += temp.get("sql");
					whereSql += temp.get("sql");
					paraKey=(List<Object>) temp.get("paraKey");
				}
				whereSql +=   wherePagesql2;
				String sql = paraMap.get("sql").toString() + whereSql;
				countSQL += countWhere;
				// 开始执行查询
				this.con = this.get_JDBC_Con();
				// 查询总记录数
				List<Map<String, Object>> totalList = mysqlExceQuerySQL(countSQL,
						con, para, false,paraKey);
				outExceSQL(para,countSQL);  //仅输出
				Map<String, Object> totalMap = totalList.get(0);
				resultMap.put("record", totalMap.get("total"));
				// 查询数据
				List<Map<String, Object>> dataRows = mysqlExceQuerySQL(sql, con,
						para, true,paraKey);
				outExceSQL(para,sql);  //仅输出
				resultMap.put(pageMap.get("tableName").toString(), dataRows);			
			} else {
				writeLog(this.getClass().getName()
						+ "出错， method:markPageSql"
						+ "pageMap集合应包涵  Id(自增列)  tableName  currentPage  pageSize 等参数");
				throw new SqlPrepareException(this.getClass().getName()
						+ "出错， method:markPageSql"
						+ "pageMap 必须包涵  tableName  currentPage  pageSize 等参数");
			}
		} catch (Exception e) {
			writeLog(this.getClass().getName()
					+ "出错， method:markPageSql"
					+ "pageMap集合应包涵  Id(自增列)  tableName  currentPage  pageSize 等参数"
					+ "  原错误消息：" + e.getMessage());
			e.printStackTrace();
		} finally {
			this.closeAll();
		}
		return resultMap;
	}
	private  void  outExceSQL(Map<String,Object> para,String sql){
		
	System.out.println("执行SQL："+sql);
	String tmpStr="执行SQL："+sql;
	writeLog(tmpStr);
	if (para != null) {
		String paraStr = "";
		
		Set<String> paraSet = para.keySet();
		for (String key : paraSet) {
			paraStr +=  "\t" + key + "：" + para.get(key) + "\t,";
		}
		System.out.println("参数为："+paraStr);
		tmpStr="参数为："+paraStr;
		writeLog(tmpStr);
	}
}
}
